import { login, logout } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    username: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(JSON.stringify({ username: username.trim(), password: password.trim() })).then(res => {
        // commit('SET_TOKEN', data.token)
        // commit('SET_USERNAME', username.trim())
        // console.log(data.token)
        // console.log(res)
        let name = res.user.userName
        console.log('name->' + name)
        if(name.trim() == '' || name.trim().length == 0){
          name = username
        }
        window.sessionStorage.setItem('name', name)
        setToken(res.user)
        // console.log(encodeURIComponent(data.token))
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getUserInfo().then(res => {
      //   if (res.userId !== null) {
      //     resolve(res)
      //   } else {
      //     router.push('/login')
      //   }
      // })
      // getInfo(state.token).then(response => {
      // const data = {
      //   roles: ['admin'],
      //   introduction: 'I am a super administrator',
      //   avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      //   name: 'Super Admin'
      // }
      // if (!data) {
      //   return reject('Verification failed, please Login again.')
      // }
      // const { name, avatar } = data
      // commit('SET_NAME', name)
      // commit('SET_AVATAR', avatar)
      resolve()
      // })
    }).catch(error => {
      reject(error)
    })
    // })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

